package com.ZeroCarbon.service.impl;

import com.ZeroCarbon.domain.po.Avatar;
import com.ZeroCarbon.exception.BusinessLogicException;
import com.ZeroCarbon.exception.FileHandingException;
import com.ZeroCarbon.mapper.AvatarMapper;
import com.ZeroCarbon.service.IAvatarService;
import com.ZeroCarbon.utils.FileHandingUtils;
import com.ZeroCarbon.utils.UserHolder;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import static com.ZeroCarbon.exception.BusinessLogicException.ERROR_EXCEPTION;
import static com.ZeroCarbon.prefix.FilePrefix.AVATAR_IMAGES;

/**
 * 个人头像信息实现类
 *
 * @since 2024-10-24
 */
@Service
@Slf4j
public class AvatarServiceImpl extends ServiceImpl<AvatarMapper, Avatar> implements IAvatarService {

    /**
     * 保存用户头像
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveAvatar(MultipartFile file) throws FileHandingException, BusinessLogicException {
        //获取用户id
        String userId = UserHolder.getUser();
        //上传头像获取文件名
        String avatarFileName = FileHandingUtils.uploadFile(AVATAR_IMAGES, file);
        //创建文件对象
        Avatar avatar = new Avatar(userId, avatarFileName);
        //获取旧的头像文件名
        String oldAvatar = getAvatar(null);
        //删除旧的头像文件
        if (!oldAvatar.contains("girl") && !oldAvatar.contains("boy")) {
            FileHandingUtils.deleteFile(oldAvatar);
        }
        try {
            //如果存在则更新头像信息
            boolean updateAvatar = updateById(avatar);
            //更新失败则抛出异常
            if (!updateAvatar) {
                throw new BusinessLogicException("更新头像信息失败");
            }
        } catch (BusinessLogicException e) {
            //输出日志
            log.debug(e.getMessage());
            //抛出业务异常
            throw new BusinessLogicException(e.getMessage());
        } catch (Exception e) {
            throw new BusinessLogicException(ERROR_EXCEPTION);
        }
    }

    /**
     * 获取用户头像
     */
    @Override
    public String getAvatar(String id) throws BusinessLogicException {
        //获取目标用户id
        String userId = id == null ? UserHolder.getUser() : id;
        //获取头像对象
        Avatar avatar;
        try {
            avatar = getById(userId);
        } catch (Exception e) {
            throw new BusinessLogicException(ERROR_EXCEPTION);
        }
        //返回头像文件名
        return avatar.getAvatarFileName();
    }
}
